package com.lsh.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/3/18 2:03 下午
 * @desc ：
 */
@Slf4j
@RequestMapping("/redisson")
@RestController
public class RedissonController {
    @Autowired
    RedissonClient redissonClient;

    @GetMapping("/getLock")
    public String  getLock(){
        RLock lock = redissonClient.getLock("RedissonLock1");
        try {
            if (lock.tryLock(2, TimeUnit.SECONDS)){
                log.info(Thread.currentThread().getName()+":获得锁成功，执行业务代码");
                Thread.sleep(5000);
                log.info(Thread.currentThread().getName()+"业务代码执行完毕，释放锁");
                lock.unlock();
            }else {
                log.error(Thread.currentThread().getName()+"获得锁失败");
                return "fail";
            }
        }catch (Exception e){
            log.error("业务代码发生异常");
            return "业务代码发生异常";
        }
        return "success";
    }

}
